package com.neo.exception;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.alibaba.fastjson.JSONObject;
import com.neo.entity.Response;

@RestControllerAdvice
public class ExceptionController {
	
	private Logger logger = LoggerFactory.getLogger(ExceptionController.class);
	
	@ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
	public String authenticationException1(HttpServletRequest request, HttpServletResponse response) {
		String value = "请求 "+request.getRequestURL()+" 没有权限";
		logger.info("==>[权限拦截] {}", value);
		if (isAjaxRequest(request)) {
            writeJson(Response.success().addData("view", value), response);
        } else {
//        	sendRedirect("/403", response);
        	try {
				WebUtils.issueRedirect(request, response, "/403");
			} catch (IOException e) {
				logger.error(ExceptionStackTrace.getExceptionInfo(e));
			}
        }
		return null;
	}
	
	private void writeJson(Object object, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			out = response.getWriter();
			out.write(JSONObject.toJSONString(object));
		} catch (IOException e) {
			logger.error("{}", ExceptionStackTrace.getExceptionInfo(e));
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	/*private void sendRedirect(String location, HttpServletResponse response) {
        try {
			response.sendRedirect(location);
		} catch (IOException e) {
			logger.error("{}", ExceptionStackTrace.getExceptionInfo(e));
		}
    }*/
	
	public boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }
}
